package com.binc.testspring.study.mina.study2;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.nio.charset.Charset;
import java.util.Objects;

/**
 * FileName: MyProtocalEncoder  自定义协议包的编码器
 *  编码就是将我们的java对象变成二进制流
 * Autho: binC
 * Date:  2022/3/25 15:25
 */
public class MyProtocolEncoder extends ProtocolEncoderAdapter {

    private final Charset charset;

    public MyProtocolEncoder(Charset charset) {
        this.charset = charset;
    }

    @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        MyProtocolPackage value = (MyProtocolPackage)message; // 我们发送的就是MyProtocolPackage，这里强制转一下
        //创建一个缓冲器  空间的话就是我们发送内容的带下
        IoBuffer buffer = IoBuffer.allocate(value.getHeadLength());
        //这是制动拓展
        buffer.setAutoExpand(true);

        //设置内容
        buffer.putInt(value.getHeadLength());
        buffer.put(value.getVersion());
        if (Objects.nonNull(value.getContent())) {
            buffer.put(value.getContent().getBytes(charset));
        }

        buffer.flip();
        out.write(buffer);
    }
}
